package se581.banker.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import se581.banker.TrackerAccount;

public class AccountQueryDao implements TrackerDao {
	static Logger logger = Logger.getLogger(AccountQueryDao.class.getName());
	

	static final String FIND_BALANCE_BY_ID_SQL = "select bal from usr_acct where ID=?";
  
    
    
   Connection conn = null;
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   
   
   private Connection getConnection() throws SQLException {
	    Connection conn;
	    conn=ConnectionFactory.getInstance().getConnection();
	    return conn;
   }
   

   /**
    * Returns account balance
    * 
    * @param accountId
    * @return
    */
   public TrackerAccount findBalanceByPrimaryKey(String accountId) {
	   
	   TrackerAccount acct = null;
	   try
	   {
		   	conn=getConnection();
		    pstmt=conn.prepareStatement(AccountQueryDao.FIND_BALANCE_BY_ID_SQL);
		    pstmt.setString(1, accountId);
		    rs=pstmt.executeQuery();
		    while (rs.next()) {
			     acct =  new TrackerAccount();
			     acct.setId(accountId);
			     acct.setBalance( rs.getInt(1) );
		    }
	   }
	   catch(SQLException e) {
		   e.printStackTrace();
	   }
	   finally {
		    try {
			    if(rs!=null)
			        rs.close();
			    if(pstmt!=null)
			       pstmt.close();
			    if(conn!=null)
			       conn.close();
		    }
		    catch(SQLException e)
		    {
		     e.printStackTrace();
		    }
		    catch(Exception e)
		    {
		     e.printStackTrace();
		    }		   
	   }
	   
	   return acct;
   }
}
